<template>
  <TaskChatDialog
    v-model="visible"
    :title="title"
    width="40%"
    @close="close"
    :close-on-click-modal="false"
    destroy-on-close>
    <el-form ref="formRef" :model="form" label-width="130px" :rules="formRules">
      <template v-if="projectFormat === 'set'">
        <el-form-item label="项目集名称：" prop="projectName">
          <el-input v-model.trim="form.projectName" maxlength="27" placeholder="请输入项目集名称" />
        </el-form-item>
      </template>
      <template v-if="projectFormat === 'item' || projectFormat === 'itemEdit'">
        <el-form-item label="项目名称：" prop="projectName">
          <el-input v-model.trim="form.projectName" maxlength="27" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目集：" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="treeData"
            :props="treeProps"
            clearable
            check-strictly
            :render-after-expand="true"
            :check-on-click-node="true"
            placeholder="请选择" />
        </el-form-item>
        <el-form-item label="归属部门：" prop="deptId">
          <el-tree-select
            v-model="form.deptId"
            :data="deptList"
            :props="deptProps"
            clearable
            check-strictly
            :render-after-expand="true"
            :check-on-click-node="true"
            placeholder="请选择" />
        </el-form-item>
        <el-form-item label="项目经理：" prop="projectManager">
          <el-select v-model="form.projectManager" placeholder="请选择" clearable filterable>
            <el-option v-for="item in userList" :key="item.value" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目类型：" prop="projectType">
          <el-select v-model="form.projectType" placeholder="请选择">
            <el-option
              v-for="(item, index) in dict.dictMap['task_project_type']"
              :key="index"
              :label="item.dictLabel"
              :value="Number(item.dictValue)" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目分类：" prop="projectClass">
          <el-select v-model="form.projectClass" placeholder="请选择">
            <el-option
              v-for="(item, index) in dict.dictMap['task_project_class']"
              :key="index"
              :label="item.dictLabel"
              :value="Number(item.dictValue)" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务编辑模式：" prop="isCreate">
          <el-select v-model="form.isCreate" placeholder="请选择" clearable filterable>
            <el-option
              v-for="(item, index) in dict.dictMap['task_edit_mode']"
              :key="index"
              :label="item.dictLabel"
              :value="Number(item.dictValue)"></el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="项目成员：" prop="tcProjectMembers">-->
        <!--  <el-select v-model="tcProjectMembers" placeholder="请选择" multiple clearable filterable>-->
        <!--    <el-option v-for="item in userList" :key="item.value" :label="item.nickName" :value="item.userId" />-->
        <!--  </el-select>-->
        <!--</el-form-item>-->
        <el-form-item label="计划时间：" prop="planBegin">
          <el-date-picker
            :model-value="[form.planBegin, form.planEnd]"
            type="daterange"
            format="YYYY-MM-DD"
            :unlink-panels="true"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="defaultTime"
            @update:modelValue="planDateChange" />
        </el-form-item>
        <el-form-item label="阶段模板选择：" prop="templateId">
          <el-select v-model="form.templateId" placeholder="请选择阶段模板" clearable filterable>
            <el-option
              v-for="(item, index) in stageTemplate"
              :key="index"
              :label="item.templateName"
              :value="item.templateId" />
          </el-select>
        </el-form-item>
        <el-form-item label="文档模板选择：" prop="dxtId">
          <el-select v-model="form.dxtId" placeholder="请选择文档模板" clearable filterable>
            <el-option v-for="(item, index) in docTemplate" :key="index" :label="item.dxtName" :value="item.dxtId" />
          </el-select>
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="onSubmit" :loading="submitLoading">提交</el-button>
      <el-button @click="close">取消</el-button>
    </template>
  </TaskChatDialog>
</template>

<script setup>
import {
  getTcTaskProjectList,
  addTcTaskProject,
  editTcTaskProject,
  getTcTaskProjectParentList,
  getProjectMember,
  getProjectDetail,
} from '@/assets/api/project'
import { ElMessage } from 'element-plus'
import { getUserList } from '@/assets/api/user'
import dayjs from 'dayjs'
import { useDictionary } from '@/use/use-dictionary'
import { getTemplateList } from '@/assets/api/stage-template'
import { getDocTemplateList } from '@/assets/api/document-template'
import { getDeptTree } from '@/assets/api/dept'
const emit = defineEmits(['refresh'])

defineExpose({
  open,
})

// 项目格式: set(项目集), item(项目)
const projectFormat = ref()

const visible = ref(false)

const title = computed(
  () => (form.value.projectId ? '修改' : '创建') + (projectFormat.value === 'set' ? '项目集' : '项目')
)

const defaultTime = reactive([new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)])

const dict = useDictionary(['task_project_type', 'task_edit_mode', 'task_project_class'])

// 表单配置
const formRef = ref()

const form = ref({})

const submitLoading = ref(false)

// const tcProjectMembers = computed({
//   get() {
//     return (form.value?.tcProjectMembers || []).map((i) => i.userId)
//   },
//   set(v) {
//     form.value.tcProjectMembers = v.map((userId) => {
//       return { userId }
//     })
//   },
// })

const formRules = reactive({
  projectName: [{ required: true, message: '项目名称不可为空', trigger: 'blur' }],
  projectType: [{ required: true, message: '项目类型不可为空', trigger: 'change' }],
  projectClass: [{ required: true, message: '项目分类不可为空', trigger: 'change' }],
  projectManager: [{ required: true, message: '项目经理不可为空', trigger: 'change' }],
  deptId: [{ required: true, message: '归属部门不可为空', trigger: 'change' }],
  isCreate: [{ required: true, message: '任务编辑模式不可为空', trigger: 'change' }],
  planBegin: [{ required: true, message: '计划时间不可为空', trigger: 'change' }],
})

// 获取项目集
const treeData = ref([])

const treeProps = reactive({
  children: 'children',
  label: 'projectName',
  value: 'projectId',
})

const deptProps = reactive({
  children: 'children',
  label: 'label',
  value: 'id',
})

// 获取阶段模板下拉框
const stageTemplate = ref([])
getStageTemplate()
function getStageTemplate() {
  getTemplateList().then((res) => {
    if (res.code === 200) {
      stageTemplate.value = res.rows
    }
  })
}
// 获取文档模板列表
const docTemplate = ref([])
getDocTemplate()
function getDocTemplate() {
  getDocTemplateList({}).then((res) => {
    if (res.code === 200) {
      docTemplate.value = res.data
    }
  })
}

function getParentList() {
  getTcTaskProjectParentList().then((res) => {
    if (res.code === 200) {
      treeData.value = res.rows
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 提交(项目/项目集)
function onSubmit() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      const isAdd = !form.value.projectId
      const data = JSON.parse(JSON.stringify(form.value))
      if (!data.parentId) {
        data.parentId = 0
      }
      const res = await (isAdd ? addTcTaskProject : editTcTaskProject)(data)
      if (res.code === 200) {
        ElMessage.success('提交成功')
        close()
        emit('refresh')
      } else {
        ElMessage.error(res.msg)
      }
      submitLoading.value = false
      // let requestApi = props.handleProjectConfig.handle === 'add' ? addTcTaskProject : editTcTaskProject
      // if (props.handleProjectConfig.type === 'set') {
      //   try {
      //     await requestApi({ ...form.value })
      //     ElMessage.success('提交成功')
      //     emit('refresh')
      //     close()
      //   } catch (error) {
      //     ElMessage.error('提交失败')
      //   }
      // } else if (props.handleProjectConfig.type === 'item') {
      //   // 数据不满足需求，临时写死
      //   if (props.handleProjectConfig.handle === 'add') {
      //     form.value = {
      //       ...form.value,
      //       tcProjectMembers: [{ userId: 111 }],
      //       projectManager: '1',
      //       projectType: '1',
      //       planBegin: (Array.isArray(form.value.daterange) && form.value.daterange[0]) || '',
      //       planEnd: (Array.isArray(form.value.daterange) && form.value.daterange[1]) || '',
      //     }
      //   }
      //
      //   try {
      //     await requestApi({ ...form.value })
      //     ElMessage.success('提交成功')
      //     emit('refresh')
      //     close()
      //   } catch (error) {
      //     ElMessage.error('提交失败')
      //   }
      // }
    }
  })
}

function planDateChange(date) {
  form.value.planBegin = date && date.length > 0 ? dayjs(date[0]).valueOf() : ''
  form.value.planEnd = date && date.length > 0 ? dayjs(date[1]).valueOf() : ''
}

const userList = ref([])

function getUserListData() {
  getUserList().then((res) => {
    if (res.code === 200) {
      userList.value = res.rows
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const deptList = ref([])
function getDeptTreeData() {
  getDeptTree().then((res) => {
    if (res.code === 200) {
      deptList.value = res.data || []
    } else {
      ElMessage.error(res.msg)
    }
  })
}

async function getProjectDetailData(projectId) {
  await getProjectDetail(projectId).then((res) => {
    if (res.code === 200) {
      const data = res.data
      data.parentId === 0 ? (data.parentId = null) : data.parentId
      form.value = data
    } else {
      ElMessage.error(res.msg)
    }
  })
}

async function open(projectId, format, parentId) {
  if (projectId) {
    await getProjectDetailData(projectId)
  }
  projectFormat.value = format
  if (format === 'item') {
    getUserListData()
    getParentList()
    getDeptTreeData()
    form.value.parentId = parentId || null
  }
  visible.value = true
}

// 关闭对话框
function close() {
  form.value = {}
  visible.value = false
}
</script>

<style lang="scss" scoped>
.elp-input,
.elp-select {
  width: 100%;
}
</style>
